cap log close 
log using "${logpath}priorauth_patlevel.log", replace

/*******************************************************************************
priorauth_patlevel.do

Conducts analysis of prior authorization at the patient panel
*******************************************************************************/

clear all

qui	use ${cleandatapath}patientlevel.dta if year>=2011, clear

qui {
	bysort usrds_id prior_auth: egen totalrides_pre=sum(NEdialysisrides) if prior_auth==0
	bysort usrds_id: egen pre_ride_tot=max(totalrides_pre)
	gen freqride=(pre_ride_tot>=100 & !missing(pre_ride_tot))

	gen postwindow=0 if priorauth_date==1 & (year==2013 | year==2014)
	replace postwindow=1 if priorauth_date==1 & (year==2015 | year==2016)
	bysort usrds_id postwindow: egen totalrides_prewindow=sum(NEdialysisrides) if postwindow==0
	bysort usrds_id postwindow: egen totalrides_postwindow=sum(NEdialysisrides) if postwindow==1
	bysort usrds_id: egen pre_totalrides=max(totalrides_prewindow) if !missing(postwindow)
	bysort usrds_id: egen post_totalrides=max(totalrides_postwindow) if !missing(postwindow)
	bysort usrds_id postwindow: egen totalridemo_prewindow=sum(any_ride) if postwindow==0
	bysort usrds_id postwindow: egen totalridemo_postwindow=sum(any_ride) if postwindow==1
	bysort usrds_id: egen pre_totalridemo=max(totalridemo_prewindow) if !missing(postwindow)
	bysort usrds_id: egen post_totalridemo=max(totalridemo_postwindow) if !missing(postwindow)
	bysort usrds_id: gen pat_flag=_n==1
	
}

su pre_totalridemo if pre_totalridemo>0 & pat_flag==1, d // Referenced in Section 5.3, Paragraph 4
su post_totalridemo if post_totalridemo>0 & pat_flag==1, d // Referenced in Section 5.3, Paragraph 4

twoway (hist pre_totalrides if pre_totalridemo>0, ///
		width(20) start(-0.00001)) ///
	(hist post_totalrides if post_totalridemo>0, ///
		width(20) start(-0.00001) fcolor(none) lcolor(black)) if pat_flag==1, ///
	xti("") yti(Empirical Probability Density) ///
	graphregion(color(white)) bgcolor(white) ///
	leg(subti("Total Rides in the...") order(1 "Pre-Period" 2 "Post-Period"))
qui graph export "${outpath}Figure_8a.pdf", as(pdf) replace // Figure 8a

twoway (hist pre_totalridemo if pre_totalridemo>0, ///
		width(0.99999) start(0.99999)) ///
	(hist post_totalridemo if post_totalridemo>0, ///
		width(0.99999) start(0.99999) fcolor(none) lcolor(black)) if pat_flag==1, ///
	xti("") yti(Empirical Probability Mass) ///
	graphregion(color(white)) bgcolor(white) ///
	leg(subti("Total Months Riding in the...") order(1 "Pre-Period" 2 "Post-Period"))
qui graph export "${outpath}Figure_8b.pdf", as(pdf) replace // Figure 8b

qui {
	xtset usrds_id t
	gen treated_nextmonth = (f.dialsess>0 & !missing(f.dialsess))
	gen rider_stays=treated_nextmonth if any_ride==1
	gen rides_nextmonth = (f.any_ride==1)
	gen rider_ridesnext = rides_nextmonth if any_ride==1
	gen switchfirm_nextmonth = (f.ambul_NPI1!=ambul_NPI1) if rides_nextmonth==1
	gen rider_switchesnext = switchfirm_nextmonth if any_ride==1

	gen ridesamefirm=(rider_stays==1 & rider_switchesnext==0) if any_ride==1
	gen ridesdifffirm_exit=(rider_stays==1 & rider_switchesnext==1 & ride_exit_now==1) if any_ride==1
	gen ridesdifffirm_noexit=(rider_stays==1 & rider_switchesnext==1 & ride_exit_now!=1) if any_ride==1
	gen treatnoride=(rider_stays==1 & rider_ridesnext==0) if any_ride==1
	gen notreatdeath=(rider_stays==0 & death==1) if any_ride==1
	gen notreathosp=(rider_stays==0 & death==0 & hosp_any==1) if any_ride==1
	gen notreatmissing=(rider_stays==0 & death==0 & hosp_any==0) if any_ride==1

	foreach var in ridesamefirm ridesdifffirm_exit ridesdifffirm_noexit treatnoride notreatdeath notreathosp notreatmissing {
		gen E`var'=`var' if ride_exit_now==1
	}
	gen Ekeepriding=max(Eridesamefirm,Eridesdifffirm_exit)

	label var Eridesamefirm "Continues Riding with Primary Firm"
	label var Eridesdifffirm_exit "Changes Primary Firm"
	label var Etreatnoride "Is Treated without Riding"
	label var Enotreatdeath "Dies This Month"
	label var Enotreathosp "Is Hospitalized This Month"
	label var Enotreatmissing "Is Not Treated Next Month"
	label var Ekeepriding "Continues Riding"

	gen PA_phase=-1 if t<658 & priorauth_date==1
	replace PA_phase=0 if (t==658 | t==659) & priorauth_date==1
	replace PA_phase=1 if t>659 & priorauth_date==1
	replace PA_phase=-1 if t<671 & priorauth_date==2
	replace PA_phase=0 if (t==671 | t==672) & priorauth_date==2
	replace PA_phase=1 if t>672 & priorauth_date==2

	estimates clear
	bysort PA_phase: eststo: estpost sum Ekeepriding Eridesdifffirm_noexit Etreatnoride Enotreatdeath Enotreathosp Enotreatmissing if t!=695 & (PA_phase==-1 | PA_phase==0)
	esttab using ${outpath}Table_A23.tex, replace ///
		drop(Eridesdifffirm_noexit) ///
		cells(mean(fmt(%4.3fc))) ///
		label booktabs nonum frag collabels(none) ///
		mtitles("Pre-Prior Auth." "At Prior Auth." "Post-Prior Auth.") ///
		mgroups("Period When Firm Exits", pattern(1 0) prefix(\multicolumn{@span}{c}{) ///
		suffix(}) span erepeat(\cmidrule(lr){@span})) // Table A23

	gen DVA=newchain==1 if !missing(newchain)
	gen FMC=newchain==2 if !missing(newchain)
	gen IND=newchain==3 if !missing(newchain)
	gen OTH=newchain==4 if !missing(newchain)

	*Patient Characteristics
	label var pat_age "\hspace*{0.5cm} Age (Years)"
	label var dial_tenure "\hspace*{0.5cm} Months with ESRD"
	label var black "\hspace*{0.5cm} Black"
	label var male "\hspace*{0.5cm} Male"
	label var inc_diabetes "\hspace*{0.5cm} Diabetic"
	label var inc_drug "\hspace*{0.5cm} Drug User"
	label var inc_smoker "\hspace*{0.5cm} Smoker"
	label var inc_drinker "\hspace*{0.5cm} Drinker"
	label var inc_noins "\hspace*{0.5cm} Uninsured at Incidence"
	label var inc_empcur "\hspace*{0.5cm} Employed at Incidence"
	*Ridership
	label var NEdialysisrides "\hspace*{0.5cm} Non-Emergency Dialysis Rides"
	label var emerg_rides "\hspace*{0.5cm} Emergency Rides"
	label var lifetime_rides "\hspace*{0.5cm} Total Lifetime Rides"
	label var rider_ridesnext "\hspace*{0.5cm} Continuing to Ride Next Month"
	*Facility Characteristics
	label var fac_age "\hspace*{0.5cm} Facility Age (Years)"
	label var fac_free "\hspace*{0.5cm} Freestanding Facility"
	label var DVA "\hspace*{1cm} DaVita"
	label var FMC "\hspace*{1cm} Fresenius"
	label var OTH "\hspace*{1cm} Other Chain"
	label var IND "\hspace*{1cm} Independent"
	*Health Outcomes
	label var dialsess "\hspace*{0.5cm} Dialysis Sessions"
	label var hosp_any "\hspace*{0.5cm} All-Cause Hosp."
	label var hosp_fluid1 "\hspace*{0.5cm} Fluid Hosp."
	label var death "\hspace*{0.5cm} Mortality"

	gen rider_cat=0 if lifetime_rides==0
	replace rider_cat=1 if lifetime_rides>0 & any_ride==0
	replace rider_cat=2 if lifetime_rides>0 & any_ride==1

	*Table 1
	eststo clear
	bysort rider_cat: eststo: estpost sum pat_age dial_tenure black male inc_diabetes inc_drug inc_smoker inc_drinker inc_noins inc_empcur NEdialysisrides emerg_rides lifetime_rides rider_ridesnext fac_age fac_free DVA FMC OTH IND dialsess hosp_any hosp_fluid1 death
	eststo: estpost sum pat_age dial_tenure black male inc_diabetes inc_drug inc_smoker inc_drinker inc_noins inc_empcur NEdialysisrides emerg_rides lifetime_rides rider_ridesnext fac_age fac_free DVA FMC OTH IND dialsess hosp_any hosp_fluid1 death
	esttab using ${outpath}Table_1.tex, replace ///
		cells(mean(fmt(%4.2fc %4.2fc %4.3fc %4.3fc %4.3fc ///
			%4.3fc %4.3fc %4.3fc %4.3fc %4.3fc ///
			%4.2fc %4.3fc %4.1fc %4.3fc ///
			%4.2fc %4.3fc %4.3fc %4.3fc %4.3fc %4.3fc ///
			%4.2fc %4.3fc %4.3fc %4.3fc))) ///
		label booktabs nonum frag collabels(none) ///
		mtitles("Never-Rider" "Rider, Non-Riding Month" "Rider, Riding Month" "Overall") ///
		mgroups("Patient Rider Status", pattern(1 0 0 1) prefix(\multicolumn{@span}{c}{) ///
		suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		refcat(pat_age "\textbf{Patient Characteristics}" ///
			   NEdialysisrides "\textbf{Ridership}" ///
			   fac_age "\textbf{Facility Characteristics}" ///
			   DVA "\hspace*{0.5cm} \textit{Chain Affiliation}" ///
			   dialsess "\textbf{Health Outcomes}", ///
			   nolabel) stats(N, label("Patient-Months") fmt(%16.0fc))

	gen PA_cat=priorauth_date-1
	replace PA_cat=3 if PA_cat==-1
	
	*Table A8
	eststo clear
	bysort PA_cat: eststo: estpost sum pat_age dial_tenure black male inc_diabetes inc_drug inc_smoker inc_drinker inc_noins inc_empcur NEdialysisrides emerg_rides lifetime_rides rider_ridesnext fac_age fac_free DVA FMC OTH IND dialsess hosp_any hosp_fluid1 death if t<659
	eststo: estpost sum pat_age dial_tenure black male inc_diabetes inc_drug inc_smoker inc_drinker inc_noins inc_empcur NEdialysisrides emerg_rides lifetime_rides rider_ridesnext fac_age fac_free DVA FMC OTH IND dialsess hosp_any hosp_fluid1 death if t<659
	esttab using ${outpath}Table_A8.tex, replace ///
		cells(mean(fmt(%4.2fc %4.2fc %4.3fc %4.3fc %4.3fc ///
			%4.3fc %4.3fc %4.3fc %4.3fc %4.3fc ///
			%4.2fc %4.3fc %4.1fc %4.3fc ///
			%4.2fc %4.3fc %4.3fc %4.3fc %4.3fc %4.3fc ///
			%4.2fc %4.3fc %4.3fc %4.3fc))) ///
		label booktabs nonum frag collabels(none) ///
		mtitles("Wave 1" "Wave 2" "Untreated" "Overall") ///
		mgroups("Prior Authorization Wave", pattern(1 0 0 1) prefix(\multicolumn{@span}{c}{) ///
		suffix(}) span erepeat(\cmidrule(lr){@span})) ///
		refcat(pat_age "\textbf{Patient Characteristics}" ///
			   NEdialysisrides "\textbf{Ridership}" ///
			   fac_age "\textbf{Facility Characteristics}" ///
			   DVA "\hspace*{0.5cm} \textit{Chain Affiliation}" ///
			   dialsess "\textbf{Health Outcomes}", ///
			   nolabel) stats(N, label("Patient-Months") fmt(%16.0fc))

*Effect of prior auth
	gen months_since=t-659 if priorauth_date==1
	replace months_since=t-672 if priorauth_date==2
	replace months_since=. if months_since<-12 | months_since>=12
	replace months_since=-50 if priorauth_date==0
	replace months_since=months_since+100
	gen post_together=months_since
	replace post_together=100 if months_since>=100 & !missing(months_since)
	
	*Getting estimates for Tables 4, 5, and 7
	local i = 1
	foreach var in dialsess death hosp_any hosp_fluid1 rider_death rider_hosp rider_ridesnext {

		estimates clear
		eststo est1: reghdfe `var' ib99.post_together $pat_controls $fac_controls, a(t newprovusrd dist_code) vce(cluster dist_code)
		eststo est1,addscalars(time_FE 1)
		eststo est1,addscalars(dist_FE 1)
		eststo est1,addscalars(Cont 1)
		eststo est1,addscalars(Fac_FE 1)
		eststo est1,addscalars(Pat_FE 0)
		estadd ysumm
		estimates save ${estpath}priorauth_`var'_posttogether,replace

		if `i'<=4 {
			estimates clear
			eststo est1: reghdfe `var' ib99.post_together $pat_controls $fac_controls if freqride==1, a(t dist_code newprovusrd) vce(cluster dist_code)
			eststo est1,addscalars(time_FE 1)
			eststo est1,addscalars(dist_FE 1)
			eststo est1,addscalars(Cont 1)
			eststo est1,addscalars(Fac_FE 1)
			eststo est1,addscalars(Pat_FE 0)
			estadd ysumm
			estimates save ${estpath}priorauth_`var'_posttogether_freqride,replace
		}
		
		local i = `i'+1
	}
		
	*Table 4
	estimates clear
	local i = 1
	foreach var in dialsess death hosp_any hosp_fluid1 {
		estimates use ${estpath}priorauth_`var'_posttogether
		estimates store est`i'
		local i = `i'+1
	}

	label var dialsess "Dialysis Sessions"
	label var death "Mortality"
	label var hosp_any "All-Cause Hosp."
	label var hosp_fluid1 "Fluid Hosp."
	label define PA 100 "Prior Auth.", replace
	label values post_together PA
	esttab est* using ${outpath}Table_4.tex, ///
		star(+ 0.1 * 0.05 ** 0.01 *** 0.001) ///
		replace keep(100.post_together) label se stats(time_FE dist_FE Cont Fac_FE r2 ymean N, ///
		label("Year-Month FE" "District FE" "Pat/Fac Controls" "Facility FE" ///
		"R-squared" "Dep. Var. Mean" "Observations")) frag	booktabs
}

di (-0.0256-1.96*0.0191)/12.12 // Referenced in Section 5.2, Paragraph 3

qui {
	*Table 5
	estimates clear
	local i = 1
	foreach var in dialsess death hosp_any hosp_fluid1 {
		estimates use ${estpath}priorauth_`var'_posttogether_freqride
		estimates store est`i'
		local i = `i'+1
	}

	label var dialsess "Dialysis Sessions"
	label var death "Mortality"
	label var hosp_any "All-Cause Hosp."
	label var hosp_fluid1 "Fluid Hosp."
	esttab est* using ${outpath}Table_5.tex, ///
		star(+ 0.1 * 0.05 ** 0.01 *** 0.001) ///
		replace keep(100.post_together) label se stats(time_FE dist_FE Cont Fac_FE r2 ymean N, ///
		label("Year-Month FE" "District FE" "Pat/Fac Controls" "Facility FE" ///
		"R-squared" "Dep. Var. Mean" "Observations")) frag	booktabs
	
	*Table 7
	estimates clear
	local i = 1
	foreach var in rider_ridesnext rider_hosp rider_death {
		estimates use ${estpath}priorauth_`var'_posttogether
		estimates store est`i'
		local i = `i'+1
	}

	label var rider_ridesnext "Rides Next Month"
	label var rider_hosp "Hospitalizations"
	label var rider_death "Mortality"
	esttab est* using ${outpath}Table_7.tex, ///
		star(+ 0.1 * 0.05 ** 0.01 *** 0.001) ///
		replace keep(100.post_together) label se stats(time_FE dist_FE Cont Fac_FE r2 ymean N, ///
		label("Year-Month FE" "District FE" "Pat/Fac Controls" "Facility FE" ///
		"R-squared" "Dep. Var. Mean" "Observations")) frag	booktabs

	label var NEdialysisrides "Ambulance Rides per Month"
	label var rider_death "Mortality Rate Among Riders"
	label var rider_hosp "Hospitalization Rate Among Riders"
}

*Figures 9, A11b
foreach var in rider_ridesnext rider_hosp rider_death NEdialysisrides {
    local varlabel : variable label `var'
	estimates clear
	qui eststo: reghdfe `var' ib99.months_since $pat_controls $fac_controls, a(t dist_code newprovusrd) vce(cluster dist_code)
	qui estimates save ${estpath}priorauth_`var'_noparboth_wFE,replace
	coefplot, recast(connected) ciopts(recast(rcap)) baselevel ///
		keep(*months_since) drop(50*) vert ///
		xline(13, lcolor(gs8) lpattern(dash)) ///
		xti(Months Since Prior Authorization) ///
		xlab(1 "-12" 4 "-9" 7 "-6" 10 "-3" 13 "0" 16 "3" 19 "6" 22 "9" 25 "12") ///
		yline(0, lcolor(gs8)) ///
		yti("`varlabel'") ylab(, angle(0)) ///
		graphregion(color(white)) bgcolor(white)
	if "`var'"=="rider_ridesnext" {
		qui graph export "${outpath}Figure_9a.pdf", as(pdf) replace
	}
	if "`var'"=="rider_hosp" {
		qui graph export "${outpath}Figure_9b.pdf", as(pdf) replace
	}
	if "`var'"=="rider_death" {
		qui graph export "${outpath}Figure_9c.pdf", as(pdf) replace
	}
	if "`var'"=="NEdialysisrides" {
		qui graph export "${outpath}Figure_A11b.pdf", as(pdf) replace
	}
}

log close